package com.compomics.proteocloud.ui;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.text.DecimalFormat;

/**
 * Custom table cell renderer class providing horizontal alignment
 * and decimal formatting capabilities.
 */
public class CustomTableCellRenderer extends DefaultTableCellRenderer {

    private final DecimalFormat formatter;

    /**
     * Class constructor defining a horizontal alignment.
     */
    public CustomTableCellRenderer(int alignment) {
        this(alignment, "0");
    }

    /**
     * Class constructor defining a horizontal alignment and a decimal format pattern.
     */
    public CustomTableCellRenderer(int alignment, String decimalFormat) {
        formatter = new DecimalFormat(decimalFormat);
        setHorizontalAlignment(alignment);
    }

    public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

        if (value instanceof Number) {
            value = formatter.format((Number) value);
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
}
